﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;

#pragma warning disable IDE0130 // 命名空间与文件夹结构不匹配
namespace zykControl
#pragma warning restore IDE0130 // 命名空间与文件夹结构不匹配
{
    [Designer(typeof(DataGridViewCheckedComboBoxDesigner))]
    public class DataGridViewCheckedComboBoxColumn : DataGridViewColumn
    {
        private readonly List<object?> mList = [];

        public DataGridViewCheckedComboBoxColumn() : base(new DataGridViewCheckedComboBoxCell())
        {
            Items = new ObjectCollection(this);
        }

        public override DataGridViewCell CellTemplate
        {
            get
            {
                return base.CellTemplate;
            }

            set
            {
                // Ensure that the cell used for the template Is a CalendarCell.
                if (value is not null && !value.GetType().IsAssignableFrom(typeof(DataGridViewCheckedComboBoxCell)))
                {
                    throw new InvalidCastException("Must be a CheckedComboBoxCell");
                }

                base.CellTemplate = value;
            }
        }

        [DesignerSerializationVisibility(DesignerSerializationVisibility.Content)]
        [Localizable(true)]
        [Category("数据")]
        [Editor("System.Windows.Forms.Design.StringCollectionEditor, System.Design, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", typeof(System.Drawing.Design.UITypeEditor))]
        public ObjectCollection Items { get; set; }

        [ListBindable(false)]
        public class ObjectCollection(DataGridViewCheckedComboBoxColumn theOwner) : IList, ICollection, IEnumerable
        {
            private readonly List<object?> mList = theOwner.mList;

            public object? this[int index]
            {
                get
                {
                    return mList[index];
                }
                set
                {
                    mList[index] = value;
                }
            }

            public bool IsReadOnly { get; private set; } = false;
            public bool IsFixedSize { get; private set; } = false;

            public int Count
            {
                get
                {
                    return mList.Count;
                }
            }

            public object SyncRoot
            {
                get
                {
                    return mList;
                }
            }

            public bool IsSynchronized { get; private set; } = true;

            public void Clear()
            {
                mList.Clear();
            }

            public void Insert(int index, object? value)
            {
                mList.Insert(index, value);
            }

            public void Remove(object? value)
            {
                mList.Remove(value);
            }

            public void RemoveAt(int index)
            {
                mList.RemoveAt(index);
            }

            public void CopyTo(Array array, int index)
            {
                ((ICollection)mList).CopyTo(array, index);
            }

            public int Add(object? value)
            {
                return ((IList)mList).Add(value);
            }

            public bool Contains(object? value)
            {
                return mList.Contains(value);
            }

            public int IndexOf(object? value)
            {
                return mList.IndexOf(value);
            }

            public IEnumerator GetEnumerator()
            {
                return mList.GetEnumerator();
            }

            public void AddRange(object[] items)
            {
                mList.AddRange(items);
            }
        }

        public override object Clone()
        {
            DataGridViewCheckedComboBoxColumn dObject = (DataGridViewCheckedComboBoxColumn)base.Clone();
            dObject.Items = Items;
            dObject.DisplayMember = DisplayMember;
            dObject.ValueMember = ValueMember;
            return dObject;
        }

        [Category("数据")]
        public string DisplayMember { get; set; } = "";
        [Category("数据")]
        public string ValueMember { get; set; } = "";

        public string GetDisplayText(string theKeysLine)
        {
            var dArray = theKeysLine.Split([','], StringSplitOptions.RemoveEmptyEntries);
            if (dArray.Length == 0)
                return "";
            string dText = "";
            foreach (var item in dArray)
            {
                var dValue = item.Trim();
                string dDisplayText = "";
                foreach (var dListItem in Items)
                {
                    if (dListItem is CheckedComboBoxItem item1)
                    {
                        if ((dValue ?? "") == (item1.Key ?? ""))
                        {
                            dDisplayText = item1.Description ?? "";
                            break;
                        }
                    }
                    else if (dListItem is string || dListItem is ValueType || string.IsNullOrEmpty(DisplayMember) || string.IsNullOrEmpty(ValueMember))
                    {
                        if ((dValue ?? "") == (dListItem.ToString() ?? ""))
                        {
                            dDisplayText = dListItem.ToString() ?? "";
                            break;
                        }
                    }
                    else if (dListItem.GetType().GetProperty(DisplayMember) is not null && dListItem.GetType().GetProperty(ValueMember) is not null)
                    {
                        try
                        {
                            if ((dValue ?? "") == (dListItem.GetType().GetProperty(ValueMember)?.GetValue(dListItem, null)?.ToString() ?? ""))
                            {
                                dDisplayText = dListItem.GetType().GetProperty(DisplayMember)?.GetValue(dListItem, null)?.ToString() ?? "";
                                break;
                            }
                        }
                        catch (Exception)
                        {
                            if ((dValue ?? "") == (dListItem.ToString() ?? ""))
                            {
                                dDisplayText = dListItem?.ToString() ?? "";
                                break;
                            }
                        }
                    }
                    else if ((dValue ?? "") == (dListItem.ToString() ?? ""))
                    {
                        dDisplayText = dListItem?.ToString() ?? "";
                        break;
                    }
                }

                if (string.IsNullOrEmpty(dDisplayText))
                    dDisplayText = dValue ?? "";
                dText += dDisplayText + ",";
            }

            if (dText.Length > 0) dText = dText[..^1];
            return dText;
        }
    }

    public class DataGridViewCheckedComboBoxCell : DataGridViewTextBoxCell
    {
        public DataGridViewCheckedComboBoxCell()
        {
            // Me.FlatStyle = FlatStyle.Standard
        }

        public override void InitializeEditingControl(int rowIndex, object initialFormattedValue, DataGridViewCellStyle dataGridViewCellStyle)
        {
            // Set the value of the editing control to the current cell value.
            base.InitializeEditingControl(rowIndex, initialFormattedValue, dataGridViewCellStyle);
            DataGridViewCheckedComboBoxColumn dColumn = (DataGridViewCheckedComboBoxColumn)OwningColumn;
            if (DataGridView == null) return;
            CheckedComboBoxEditingControl ctl = (CheckedComboBoxEditingControl)DataGridView.EditingControl;
            ctl.SetItems(dColumn.Items, dColumn.DisplayMember, dColumn.ValueMember);
            if (Value is null || ReferenceEquals(Value, DBNull.Value))
            {
                ctl.Value = "";
            }
            else
            {
                ctl.Value = Value.ToString() ?? "";
            }
        }

        public override Type EditType
        {
            get
            {
                // Return the type of the editing contol that CalendarCell uses.
                return typeof(CheckedComboBoxEditingControl);
            }
        }

        public override Type ValueType
        {
            get
            {
                return typeof(DataGridViewCheckedComboBoxValue);
            }
        }

        public override object? DefaultNewRowValue
        {
            get
            {
                return null;
            }
        }

        public override bool ReadOnly { get; set; } = true;

        protected override object? GetFormattedValue(object value, int rowIndex, ref DataGridViewCellStyle cellStyle, TypeConverter valueTypeConverter, TypeConverter formattedValueTypeConverter, DataGridViewDataErrorContexts context)
        {
            if (value is null) return null;
            string dText = ((DataGridViewCheckedComboBoxColumn)OwningColumn).GetDisplayText(value.ToString() ?? "");
            return dText;
        }

        public override object? ParseFormattedValue(object formattedValue, DataGridViewCellStyle cellStyle, TypeConverter formattedValueTypeConverter, TypeConverter valueTypeConverter)
        {
            if (formattedValue is null) return null;
            if (formattedValue is DataGridViewCheckedComboBoxValue value)
            {
                return value.Value;
            }
            else
            {
                return formattedValue;
            }
        }
    }

    internal class DataGridViewCheckedComboBoxValue
    {
        public string Value { get; set; } = "";
        public string DisplayText { get; set; } = "";

        public override string ToString()
        {
            return DisplayText ?? "";
        }
    }

    class CheckedComboBoxEditingControl : CheckedComboBox, IDataGridViewEditingControl
    {
        public CheckedComboBoxEditingControl()
        {
        }

        public void SetItems(DataGridViewCheckedComboBoxColumn.ObjectCollection theItems, string theDisplayMember, string theValueMember)
        {
            if (theItems is not null)
            {
                DisplayMember = theDisplayMember;
                ValueMember = theValueMember;
                Items.Clear();
                foreach (var dItem in theItems)
                    Items.Add(dItem);
                RefreshCheckedComboBoxSelection();
                SelectedIndex = -1;
            }
        }

        // Implements the IDataGridViewEditingControl.EditingControlFormattedValue 
        // property.
        public object EditingControlFormattedValue
        {
            get
            {
                return new DataGridViewCheckedComboBoxValue() { DisplayText = Text, Value = Value };
            }

            set
            {
                if (value is null)
                {
                    Value = "";
                }
                else if (value is DataGridViewCheckedComboBoxValue value1)
                {
                    Value = value1.Value;
                }
                else
                {
                    Value = value.ToString() ?? "";
                }
            }
        }

        // Implements the 
        // IDataGridViewEditingControl.GetEditingControlFormattedValue method.
        public object GetEditingControlFormattedValue(DataGridViewDataErrorContexts context)
        {
            return EditingControlFormattedValue;
        }

        // Implements the 
        // IDataGridViewEditingControl.ApplyCellStyleToEditingControl method.
        public void ApplyCellStyleToEditingControl(DataGridViewCellStyle dataGridViewCellStyle)
        {
            Font = dataGridViewCellStyle.Font;
            ForeColor = dataGridViewCellStyle.ForeColor;
            BackColor = dataGridViewCellStyle.BackColor;
            TextAlign = (ContentAlignment)dataGridViewCellStyle.Alignment;
        }

        // Implements the IDataGridViewEditingControl.EditingControlRowIndex 
        // property.
        public int EditingControlRowIndex { get; set; }

        // Implements the IDataGridViewEditingControl.EditingControlWantsInputKey 
        // method.
        public bool EditingControlWantsInputKey(Keys key, bool dataGridViewWantsInputKey)
        {
            // Let the DateTimePicker handle the keys listed.
            switch (key & Keys.KeyCode)
            {
                case Keys.Left:
                case Keys.Up:
                case Keys.Down:
                case Keys.Right:
                case Keys.Home:
                case Keys.End:
                case Keys.PageDown:
                case Keys.PageUp:
                    {
                        return true;
                    }

                default:
                    {
                        return false;
                    }
            }
        }

        // Implements the IDataGridViewEditingControl.PrepareEditingControlForEdit 
        // method.
        public void PrepareEditingControlForEdit(bool selectAll)
        {
            // No preparation needs to be done.
        }

        // Implements the IDataGridViewEditingControl
        // .RepositionEditingControlOnValueChange property.
        public bool RepositionEditingControlOnValueChange
        {
            get
            {
                return false;
            }
        }

        // Implements the IDataGridViewEditingControl
        // .EditingControlDataGridView property.
        public DataGridView? EditingControlDataGridView { get; set; }

        // Implements the IDataGridViewEditingControl
        // .EditingControlValueChanged property.
        public bool EditingControlValueChanged { get; set; } = false;

        // Implements the IDataGridViewEditingControl
        // .EditingPanelCursor property.
        public Cursor EditingPanelCursor
        {
            get
            {
                return base.Cursor;
            }
        }

        protected override void OnTextChanged(EventArgs eventargs)
        {
            // Notify the DataGridView that the contents of the cell
            // have changed.
            EditingControlValueChanged = true;
            EditingControlDataGridView?.NotifyCurrentCellDirty(true);
            base.OnTextChanged(eventargs);
        }
    }

    internal class DataGridViewCheckedComboBoxDesigner : System.ComponentModel.Design.ComponentDesigner
    {
        protected override void PreFilterProperties(IDictionary properties)
        {
            base.PreFilterProperties(properties);
        }
    }
}